package com.qf.web.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebListener
public class MySessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        ServletContext servletContext = session.getServletContext();
        //获取在线人数
        Object countObj = servletContext.getAttribute("count");
        if(countObj == null) {
            servletContext.setAttribute("count", 1);
        }else{
            //在线人数 加一
            servletContext.setAttribute("count", (int)countObj + 1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        ServletContext servletContext = session.getServletContext();

        Object countObj = servletContext.getAttribute("count");
        if(countObj == null) {
            servletContext.setAttribute("count", 1);
        }else{
            servletContext.setAttribute("count", (int)countObj - 1);
        }
    }
}
